<template>
  <div>
    <h1>商品分类</h1>
    <!-- 搜索 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="分类名称:">
          <el-input
            v-model="searchForm.typeName"
            placeholder="请输入分类名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类状态:">
          <el-select
            v-model="searchForm.typeStatus"
            placeholder="请选择商品分类状态"
            style="width: 180px"
            clearable
          >
            <el-option label="显示" :value="0" />
            <el-option label="隐藏" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加分类 -->
    <div>
      <el-button type="primary" @click="toAddType">添加分类</el-button>
    </div>
    <!-- 分类列表 -->
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="typeName" label="分类名称" />
        <el-table-column prop="typeImage" label="分类图片">
          <template #default="scope">
            <el-image
              :src="scope.row.typeImage"
              v-if="scope.row.typeImage != null"
              style="width: 50px; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="typeTop" label="排序" />
        <el-table-column prop="typeStatus" label="状态">
          <template #default="scope">
            <span v-if="scope.row.typeStatus == 0">显示</span>
            <span v-if="scope.row.typeStatus == 1">隐藏</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template #default="scope">
            <el-button type="primary" @click="toAddChild(scope.row)"
              >添加</el-button
            >
            <el-button type="success">隐藏</el-button>
            <el-button type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="分类名称"
            :label-width="formLabelWidth"
            prop="typeName"
          >
            <el-input v-model="form.typeName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="分类图片"
            :label-width="formLabelWidth"
            prop="typeImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/goods/index/uploadFile"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="排序"
            :label-width="formLabelWidth"
            prop="typeTop"
          >
            <el-input v-model="form.typeTop" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="状态"
            :label-width="formLabelWidth"
            prop="typeStatus"
          >
            <el-radio-group v-model="form.typeStatus">
              <el-radio :value="0">显示</el-radio>
              <el-radio :value="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确认
            </el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getTypeList, addType } from "@/api/api";
import { useRouter } from "vue-router";
import { ElMenu, ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps } from "element-plus";
const ruleFormRef = ref<FormInstance>();
import type { FormInstance, FormRules } from "element-plus";

const router = useRouter();
const tableData = ref([]);
const total = ref(0);
const imageUrl = ref("");
const title = ref("添加类型");
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = ref({
  createBy: null,
  createTime: null,
  typeId: null,
  typeImage: null,
  typeName: null,
  typePid: null,
  typeStatus: 0,
  typeTop: null,
  updateBy: null,
  updateTime: null,
});
const restForm = () => {
  form.value = {
    createBy: null,
    createTime: null,
    typeId: null,
    typeImage: null,
    typeName: null,
    typePid: null,
    typeStatus: 0,
    typeTop: null,
    updateBy: null,
    updateTime: null,
  };
  imageUrl.value = "";
};
//添加子级
const toAddChild = (row: any) => {
  title.value = "添加类型";
  restForm();
  form.value.typePid = row.typeID;
  dialogFormVisible.value = true;
};
//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.value.typeImage = imageUrl.value;
      addType(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadList();
          restForm();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const rules = ref<FormRules<any>>({
  typeName: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  typeTop: [
    {
      pattern: /^\d+$/,
      required: true,
      message: "排序不能为空",
      trigger: "blur",
    },
  ],
  typeImage: [
    {
      validator(rule: any, value: any, callback: any) {
        if (imageUrl.value === "" || imageUrl.value == null) {
          callback(new Error("图片不能为空"));
        } else {
          callback();
        }
      },
      required: true,
      message: "图片不能为空",
      trigger: "change",
    },
  ],
  typeStatus: [
    {
      required: true,
      message: "分类状态不能为空",
      trigger: "change",
    },
  ],
});

const headers = ref({
  token: sessionStorage.getItem("token"),
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};

const searchForm = ref({
  typeName: "",
  typeStatus: "",
});
//添加分类
const toAddType = () => {
  title.value = "添加类型";
  form.value.typePid = 0;
  dialogFormVisible.value = true;
};

const loadList = () => {
  getTypeList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data;
    }
  });
};
onMounted(() => {
  loadList();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
